package ru.spbsu.electromenu.storage.db;

import org.springframework.jdbc.core.RowMapper;
import ru.spbsu.electromenu.model.Dish;
import ru.spbsu.electromenu.storage.DishStorage;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Date: 3/20/11
 * Time: 1:07 PM
 *
 * @author Artem Titov
 */
public class DishDbStorage extends AbstractDbStorage implements DishStorage {

    private final RowMapper<Dish> DISH_ROW_MAPPER = new RowMapper<Dish>() {
        @Override
        public Dish mapRow(ResultSet rs, int i) throws SQLException {
            final Dish dish = new Dish();
            dish.setId(rs.getInt("Id"));
            dish.setName(rs.getString("Name"));
            dish.setDescription(rs.getString("Description"));
            dish.setPrice(rs.getDouble("Price"));
            dish.setImage(rs.getString("Picture"));
            dish.setAvailable(rs.getBoolean("Available"));
            dish.setTagId(rs.getInt("TagId"));
            return dish;
        }
    };

    @Override
    public Dish get(int id) {
        return jdbcTemplate.queryForObject("select * from `Dish` where `Id`=?", DISH_ROW_MAPPER, id);
    }

    @Override
    public int put(Dish dish) {
        return jdbcTemplate.update("insert into `Dish`(`Name`, `Description`, `Price`, `Picture`, `TagId`, `Available`) values(?, ?, ?, ?, ?, ?)",
                dish.getName(),
                dish.getDescription(),
                dish.getPrice(),
                dish.getImage(),
                dish.getTagId(),
                dish.isAvailable());
    }

    @Override
    public int update(Dish dish) {
        return jdbcTemplate.update("update `Dish` set `Name`=?, `Description`=?, `Price`=?, `Picture`=?, `TagId`=?, `Available`=? " +
                "where `Id`=?",
                dish.getName(),
                dish.getDescription(),
                dish.getPrice(),
                dish.getImage(),
                dish.getTagId(),
                dish.isAvailable(),
                dish.getId());
    }

    @Override
    public int delete(int id) {
        return jdbcTemplate.update("delete from `Dish` where `Id`=?", id);
    }

    @Override
    public List<Dish> getALl() {
        return jdbcTemplate.query("select * from `Dish`", DISH_ROW_MAPPER);
    }
}
